package com.xiaozhen.device.controller;

import com.xiaozhen.common.core.domain.AjaxResult;
import com.xiaozhen.common.core.domain.device.DeviceCategory;
import com.xiaozhen.device.service.DeviceCategoryService;
import com.xiaozhen.security.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * HISTORY
 *
 * @author zhenweisheng
 * @date 2021/11/1 11:28
 * @description:
 */
@Api(tags = "设备分类接口")
@RestController
@RequestMapping("deviceCategory")
public class DeviceCategoryController extends BaseController {

    @Autowired
    private DeviceCategoryService deviceCategoryService;

    @ApiOperation("获取设备分类列表")
    @GetMapping("/list")
    public AjaxResult list(DeviceCategory deviceCategory) {
        List<DeviceCategory> deviceCategoryList = deviceCategoryService.selectDeviceCategoryList(deviceCategory);
        return AjaxResult.success(deviceCategoryList);
    }

    @ApiOperation("新增设备分类")
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody DeviceCategory deviceCategory) {
        if (!deviceCategoryService.checkDeviceCategoryNameUnique(deviceCategory)) {
            return AjaxResult.error("新增设备分类'" + deviceCategory.getCategoryName() + "'失败，设备分类名称已存在");
        }
        deviceCategory.setCreateBy(getCurrentUserId());
        deviceCategory.setCreateTime(LocalDateTime.now());
        return toAjax(deviceCategoryService.insertDeviceCategory(deviceCategory));
    }

    @ApiOperation("修改设备分类")
    @PutMapping("/update")
    public AjaxResult edit(@Validated @RequestBody DeviceCategory deviceCategory) {
        if (!deviceCategoryService.checkDeviceCategoryNameUnique(deviceCategory)) {
            return AjaxResult.error("修改设备分类'" + deviceCategory.getCategoryName() + "'失败，设备分类名称已存在");
        }
        if (deviceCategory.getParentId().equals(deviceCategory.getCategoryId())) {
            return AjaxResult.error("修改设备分类'" + deviceCategory.getCategoryName() + "'失败，上级设备分类不能是自己");
        }
        deviceCategory.setUpdateBy(getCurrentUserId());
        deviceCategory.setUpdateTime(LocalDateTime.now());
        return toAjax(deviceCategoryService.updateDeviceCategory(deviceCategory));
    }

    @ApiOperation("删除设备分类")
    @DeleteMapping("/{deviceCategoryId}")
    public AjaxResult remove(@PathVariable Long deviceCategoryId) {
        if (deviceCategoryService.hasChildByDeviceCategoryId(deviceCategoryId)) {
            return AjaxResult.error("存在下级设备分类,不允许删除");
        }
        if (deviceCategoryService.checkDeviceCategoryExistDevice(deviceCategoryId)) {
            return AjaxResult.error("设备分类下存在设备,不允许删除");
        }
        return toAjax(deviceCategoryService.deleteDeviceCategoryById(deviceCategoryId));
    }
}
